import styles from './ballCard.module.scss';
import { GiBasketballJersey } from 'react-icons/gi';
import { IPropsBall } from './ballCard.types';
import Button from '../button/button';
import { addToFavorite } from '../../store/balls/balls.slice';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { fetchCartPostSlice } from '../../store/cart/cart.actions';
import { addBallToCart, deleteBallOnCart } from '../../store/cart/cart.slice';
import { fetchAddFavoritesBallSlice, fetchGetFavoritesBallSlice } from '../../store/favorites/favorites.actions';
import { useEffect } from 'react';


export const BallCard = ({ ball }: IPropsBall) => {
	const dispatch = useAppDispatch();
	
	const {favoritesBalls, success, loading} = useAppSelector(state => state.addFavoriteBall);
	useEffect(() => {
	}, [success]);
	console.log('favoritesBalls', favoritesBalls);
	const {token} = useAppSelector(state => state.authorization.user);
	const {balls} = useAppSelector(state => state.cart);
	
	const addBallOnCart = (e: React.MouseEvent<HTMLButtonElement>) => {
		e.stopPropagation();
		// dispatch(fetchCartPostSlice(ball));
		{hasOnCart === true ? dispatch(deleteBallOnCart(ball.id)): dispatch(addBallToCart(ball));}
	};
	const hasOnCart = balls.some(item => item.id === ball.id);
	
	const hasOnFavorites = favoritesBalls.some(item => item.id === ball.id);
	console.log('hasOnFavorites', hasOnFavorites);
	// const toggleFavoriteBall = (e: React.MouseEvent<HTMLSpanElement>) => {
	// 	e.stopPropagation();
	// 	if (hasOnFavorites === false) {
	// 		fetchAddItemBallOnFavorite();
	// 	} fetchDeleteItemBallOnFavorite();
	// };
	
	const fetchAddItemBallOnFavorite = (e: React.MouseEvent<HTMLSpanElement>) => {
		e.stopPropagation(),
		// dispatch(addToFavorite(ball.id));
		dispatch(fetchAddFavoritesBallSlice(ball));
	};
	const fetchDeleteItemBallOnFavorite = (e: React.MouseEvent<HTMLSpanElement>) => {
		e.stopPropagation(),
		dispatch(fetchAddFavoritesBallSlice(ball.id));
	};
	return (
		<>{
			loading === false ? 
				<div className={styles.ball_cart} onClick={() => console.log(ball.id)}>
					<span
						onClick={fetchAddItemBallOnFavorite}
						className={styles.form}
					>
						<GiBasketballJersey
							color={hasOnFavorites ? '#ff0000' : '#ffa500'}
							size={40}
						/>
					</span>
					<div>
						<div className={styles.img}>
							<img src={ball.image} width={300} />
						</div>
						<div className={styles.price}>
							<p>Цена {ball.price} р</p>
							<Button deleted={hasOnCart ? true : false} disabled={token !== null ? false : true} onClick={addBallOnCart} appearance="small">
								{hasOnCart !== true ? 'В корзину': 'Удалить'}
							</Button>
						</div>
						<div className={styles.description}>
							<p className={styles.item}>Описание:</p>
							<p>{ball.title}</p>
						</div>
					</div>
				</div>
				: 
				<p>pfuheprf</p>
		}</>
		
	);
};
